<script setup lang="ts">
defineOptions({
  name: 'LoginModal',
})

import { ref, computed, watch } from 'vue'
import {
  PhX,
  PhUserCircle,
  PhEnvelope,
  PhLock,
  PhSignIn,
  PhLightning,
  PhShieldCheck
} from '@phosphor-icons/vue'

interface Props {
  show?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  show: false,
})

const emit = defineEmits<{
  close: []
  login: [email: string, password: string]
  quickLogin: []
}>()

// 表单数据
const formData = ref({
  email: '',
  password: '',
  rememberMe: false,
})

// 表单验证
const errors = ref({
  email: '',
  password: '',
})

// 加载状态
const isLoading = ref(false)

// 登录模式：'normal' | 'quick'
const loginMode = ref<'normal' | 'quick'>('normal')

// 计算属性
const isFormValid = computed(() => {
  return (
    formData.value.email.trim() !== '' &&
    formData.value.password.trim() !== '' &&
    !errors.value.email &&
    !errors.value.password
  )
})

// 验证邮箱
const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

// 验证表单
const validateForm = (): boolean => {
  errors.value.email = ''
  errors.value.password = ''

  if (!formData.value.email.trim()) {
    errors.value.email = '请输入邮箱地址'
    return false
  }

  if (!validateEmail(formData.value.email)) {
    errors.value.email = '请输入有效的邮箱地址'
    return false
  }

  if (!formData.value.password.trim()) {
    errors.value.password = '请输入密码'
    return false
  }

  if (formData.value.password.length < 6) {
    errors.value.password = '密码长度至少6位'
    return false
  }

  return true
}

// 处理普通登录
const handleLogin = async (): Promise<void> => {
  if (!validateForm()) return

  isLoading.value = true
  try {
    emit('login', formData.value.email, formData.value.password)
  } finally {
    isLoading.value = false
  }
}

// 处理快速登录
const handleQuickLogin = async (): Promise<void> => {
  isLoading.value = true
  try {
    emit('quickLogin')
  } finally {
    isLoading.value = false
  }
}

// 关闭模态框
const handleClose = (): void => {
  emit('close')
}

// 重置表单
const resetForm = (): void => {
  formData.value = {
    email: '',
    password: '',
    rememberMe: false,
  }
  errors.value = {
    email: '',
    password: '',
  }
  loginMode.value = 'normal'
}

// 监听显示状态，重置表单
watch(
  () => props.show,
  (newShow) => {
    if (newShow) {
      resetForm()
    }
  },
)

// 处理键盘事件
const handleKeydown = (event: KeyboardEvent): void => {
  if (event.key === 'Enter' && isFormValid.value && !isLoading.value) {
    handleLogin()
  }
  if (event.key === 'Escape') {
    handleClose()
  }
}
</script>

<template>
  <!-- 模态框遮罩 -->
  <Transition
    enter-active-class="transition-all duration-300 ease-out"
    enter-from-class="opacity-0"
    enter-to-class="opacity-100"
    leave-active-class="transition-all duration-200 ease-in"
    leave-from-class="opacity-100"
    leave-to-class="opacity-0"
  >
    <div
      v-if="show"
      class="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4"
      @click="handleClose"
      @keydown="handleKeydown"
    >
      <!-- 登录面板 -->
      <Transition
        enter-active-class="transition-all duration-300 ease-out"
        enter-from-class="transform scale-95 opacity-0 -translate-y-4"
        enter-to-class="transform scale-100 opacity-100 translate-y-0"
        leave-active-class="transition-all duration-200 ease-in"
        leave-from-class="transform scale-100 opacity-100 translate-y-0"
        leave-to-class="transform scale-95 opacity-0 -translate-y-4"
      >
        <div
          v-if="show"
          @click.stop
          class="bg-base-100 rounded-3xl shadow-2xl border border-base-300/50 w-full max-w-md overflow-hidden"
        >
          <!-- 头部 -->
          <div class="relative p-8 pb-6 bg-gradient-to-br from-primary/5 to-secondary/5">
            <button
              @click="handleClose"
              class="absolute top-4 right-4 btn btn-ghost btn-sm btn-circle hover:btn-error transition-all duration-200"
            >
              <PhX :size="18" />
            </button>

            <div class="text-center">
              <div
                class="w-16 h-16 bg-gradient-to-r from-primary to-secondary rounded-2xl flex items-center justify-center text-primary-content text-2xl mx-auto mb-4 shadow-lg"
              >
                <PhUserCircle :size="48" />
              </div>
              <h2 class="text-2xl font-bold text-base-content mb-2">欢迎回来</h2>
              <p class="text-base-content/60">登录您的账户继续使用</p>
            </div>
          </div>

          <!-- 登录表单 -->
          <div class="p-8 pt-6">
            <!-- 登录模式切换 -->
            <div class="flex gap-2 mb-6">
              <button
                @click="loginMode = 'normal'"
                :class="[
                  'flex-1 py-2 px-4 rounded-xl font-medium transition-all duration-200',
                  loginMode === 'normal'
                    ? 'bg-primary text-primary-content shadow-lg'
                    : 'bg-base-200 text-base-content hover:bg-base-300',
                ]"
              >
                账号登录
              </button>
              <button
                @click="loginMode = 'quick'"
                :class="[
                  'flex-1 py-2 px-4 rounded-xl font-medium transition-all duration-200',
                  loginMode === 'quick'
                    ? 'bg-primary text-primary-content shadow-lg'
                    : 'bg-base-200 text-base-content hover:bg-base-300',
                ]"
              >
                快速登录
              </button>
            </div>

            <!-- 普通登录表单 -->
            <form v-if="loginMode === 'normal'" @submit.prevent="handleLogin" class="space-y-4">
              <!-- 邮箱输入 -->
              <div class="form-control">
                <label class="label">
                  <span class="label-text font-medium">邮箱地址</span>
                </label>
                <div class="relative">
                  <input
                    v-model="formData.email"
                    type="email"
                    placeholder="请输入邮箱地址"
                    :class="[
                      'input input-bordered w-full pl-12 transition-all duration-200',
                      errors.email ? 'input-error' : 'focus:input-primary',
                    ]"
                    :disabled="isLoading"
                  />
                  <i
                    <PhEnvelope :size="16" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-base-content/50" />
                  ></i>
                </div>
                <label v-if="errors.email" class="label">
                  <span class="label-text-alt text-error">{{ errors.email }}</span>
                </label>
              </div>

              <!-- 密码输入 -->
              <div class="form-control">
                <label class="label">
                  <span class="label-text font-medium">密码</span>
                </label>
                <div class="relative">
                  <input
                    v-model="formData.password"
                    type="password"
                    placeholder="请输入密码"
                    :class="[
                      'input input-bordered w-full pl-12 transition-all duration-200',
                      errors.password ? 'input-error' : 'focus:input-primary',
                    ]"
                    :disabled="isLoading"
                  />
                  <i
                    <PhLock :size="16" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-base-content/50" />
                  ></i>
                </div>
                <label v-if="errors.password" class="label">
                  <span class="label-text-alt text-error">{{ errors.password }}</span>
                </label>
              </div>

              <!-- 记住我 -->
              <div class="form-control">
                <label class="label cursor-pointer justify-start gap-3">
                  <input
                    v-model="formData.rememberMe"
                    type="checkbox"
                    class="checkbox checkbox-primary"
                    :disabled="isLoading"
                  />
                  <span class="label-text">记住我</span>
                </label>
              </div>

              <!-- 登录按钮 -->
              <button
                type="submit"
                :disabled="!isFormValid || isLoading"
                class="btn btn-primary w-full gap-2 shadow-lg hover:shadow-xl transition-all duration-200"
                :class="{ loading: isLoading }"
              >
                <PhSignIn v-if="!isLoading" :size="18" />
                {{ isLoading ? '登录中...' : '登录' }}
              </button>
            </form>

            <!-- 快速登录 -->
            <div v-else class="text-center space-y-6">
              <div class="bg-base-200/50 rounded-2xl p-6">
                <div
                  class="w-20 h-20 bg-gradient-to-r from-success to-info rounded-full flex items-center justify-center text-white text-3xl mx-auto mb-4"
                >
                  <PhLightning :size="48" />
                </div>
                <h3 class="text-lg font-semibold text-base-content mb-2">快速体验</h3>
                <p class="text-base-content/60 text-sm mb-4">无需注册，一键登录体验所有功能</p>
                <div class="flex items-center justify-center gap-2 text-xs text-base-content/50">
                  <PhShieldCheck :size="14" />
                  <span>安全 · 快速 · 便捷</span>
                </div>
              </div>

              <button
                @click="handleQuickLogin"
                :disabled="isLoading"
                class="btn btn-primary btn-lg w-full gap-3 shadow-lg hover:shadow-xl transition-all duration-200"
                :class="{ loading: isLoading }"
              >
                <PhLightning v-if="!isLoading" :size="20" />
                {{ isLoading ? '登录中...' : '快速登录' }}
              </button>
            </div>

            <!-- 底部链接 -->
            <div class="text-center mt-6 pt-6 border-t border-base-300/30">
              <p class="text-sm text-base-content/60">
                还没有账户？
                <a href="#" class="link link-primary font-medium hover:link-hover">立即注册</a>
              </p>
            </div>
          </div>
        </div>
      </Transition>
    </div>
  </Transition>
</template>

<style scoped>
/* 输入框聚焦效果 */
.input:focus {
  box-shadow: 0 0 0 3px hsl(var(--p) / 0.2);
}

.input-error:focus {
  box-shadow: 0 0 0 3px hsl(var(--er) / 0.2);
}

/* 按钮悬停效果 */
.btn-primary:not(:disabled):hover {
  transform: translateY(-1px);
}

/* 复选框样式 */
.checkbox:checked {
  animation: checkboxPulse 0.3s ease;
}

@keyframes checkboxPulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

/* 模态框动画优化 */
.modal-backdrop {
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
}

/* 无障碍访问 */
@media (prefers-reduced-motion: reduce) {
  * {
    animation: none !important;
    transition: none !important;
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .bg-base-100 {
    margin: 1rem;
    border-radius: 1.5rem;
  }
}
</style>
